package com.example.demo.leetcode;

public class _82_删除排序链表中的重复元素Ⅱ {

    public static void main(String[] args) {
        ListNode node = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(3, new ListNode(4, new ListNode(4, new ListNode(5)))))));
        ListNode node1 = deleteDuplicates(node);
        System.out.println();
    }

    public static ListNode deleteDuplicates(ListNode head) {

        ListNode preHead = new ListNode();
        ListNode current = preHead;

        ListNode prev = null;
        ListNode next = head;
        Integer value = null;

        while (next != null) {
            if (prev == null) {
                prev = next;
                next = next.next;
            } else {
                if (prev.val == next.val) {
                    value = prev.val;
                    next = next.next;
                } else {
                    if (value != null && prev.val == value) {
                        prev = next;
                        value = null;
                        next = next.next;
                    } else {
                        current.next = new ListNode(prev.val);
                        current = current.next;
                        prev = next;
                        next = next.next;
                    }
                }
            }
        }
        if (prev != null && !Integer.valueOf(prev.val).equals(value)) {
            current.next = new ListNode(prev.val);
        }
        return preHead.next;
    }


}
